package zcj.stu;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.List;

@Configuration
@ComponentScan//扫描所在类包及其子包
@PropertySource("classpath:application.properties")
@EnableConfigurationProperties({WebMvcProperties.class, ServerProperties.class})
public class WebConfig {
    //利用内嵌web容器工厂创建web容器
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(ServerProperties serverProperties){
           return new TomcatServletWebServerFactory(serverProperties.getPort());
    }
    //创建dispatchServlet
    @Bean
    public DispatcherServlet dispatcherServlet(){
         return new DispatcherServlet();
    }
    //将dispatchServlet注册到web容器中
    @Bean
    public DispatcherServletRegistrationBean registrationBean(DispatcherServlet dispatcherServlet,WebMvcProperties webMvcProperties){
        DispatcherServletRegistrationBean registrationBean =
                new DispatcherServletRegistrationBean(dispatcherServlet, "/");
        registrationBean.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());
        return registrationBean;//所有路径
    }
    //如果容器提供了这些组件就会直接走容器组件 不另外创建默认
    @Bean
    public RequestMappingHandlerMapping handlerMapping(){
           return new RequestMappingHandlerMapping();
    }
    @Bean
    public RequestMappingHandlerAdapter adapter(){
        RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
        adapter.setCustomArgumentResolvers(List.of(new TokenArgumentResolver()));
        adapter.setReturnValueHandlers(List.of(new ZcjLReturnValueHandler()));
        return adapter;
    }
}
